
#include "common.h"
#include "md5.h"

static unsigned char *key_generate(const char *str, const int size);

static unsigned char *key_generate(const char *str, const int size)
{
	if(!str)
		return NULL;
	
	if(size < 0)
		return NULL;

	unsigned char *digest = mempool_alloc(DIGEST_LENGTH);
	assert(digest);

	MD5_CTX c;
	MD5_Init(&c);
	MD5_Update(&c, str, size);
	MD5_Final(digest, &c);
	
	return digest;
}

char *cache_key_ascii(const unsigned char *digest, const int size)
{
	char *ascii_digest = mempool_alloc(size * 2);
	int i;
	
	for(i = 0; i < size; i++) 
		snprintf(ascii_digest + 2*i, 32, "%02x", digest[i]);

	ascii_digest[size * 2] = '\0';

	return ascii_digest;
}

unsigned char *cache_key_private(const char *uri, int size)
{
	if(!uri)
		return NULL;

	char buf[MAX_BUFFER];
	int res; 

	res = snprintf(buf, MAX_URL - 1, "private:%s", uri);

	return key_generate(buf, res);
}

unsigned char *cache_key_public(const char *uri, int size)
{
	if(!uri)
		return NULL;

	char buf[MAX_URL];
	int res; 

	res = snprintf(buf, MAX_URL - 1, "public:%s", uri);

	return key_generate(buf, res);
}
